<template>

  <div class="box">
    <div class="top">
      <div class="infoTip">
        <div class="other">
          {{"当前所在城市：成都"}}
        </div>
        <div class="webTitle">国内疫情汇总</div>
        <div class="updateTime">
          <view>{{time}}</view>
          <view></view>
        </div>
      </div>
    </div>
    <div class="dataBox">
      <div class="left">
        <div class="box-left-card">
          <section>
            <div class='card-title'>本土现有确诊</div>
            <div class="nowData">
              <span :class="[store.chinaTotal.localConfirm > 0?'redFont':'greenFont']">
                {{ store.chinaTotal.localConfirm }}
              </span>
            </div>
            <div class="complete">较上日
              <span :class="[store.chinaAdd.localConfirmH5 > 0?'redFont':'greenFont']">
                {{ store.chinaAdd.localConfirmH5 > 0?"+":"-" }}{{ store.chinaAdd.localConfirmH5 }}
              </span>
            </div>
          </section>
          <section>
            <div class='card-title'>现有确诊</div>
            <div class="nowData">
              <span :class="[store.chinaTotal.nowConfirm > 0?'redFont':'greenFont']">
                {{ store.chinaTotal.nowConfirm }}
              </span>
            </div>
            <div class="complete">较上日
              <span :class="[store.chinaAdd.nowConfirm > 0?'redFont':'greenFont']">
                {{ store.chinaAdd.nowConfirm > 0?"+":"-" }}{{ store.chinaAdd.nowConfirm }}
              </span>
            </div>
          </section>
          <section>
            <div class='card-title'>累计确诊</div>
            <div class="nowData">
              <span :class="[store.chinaTotal.confirm > 0?'redFont':'greenFont']">
                {{ store.chinaTotal.confirm }}
              </span>
            </div>
            <div class="complete">较上日
              <span :class="[store.chinaAdd.confirm > 0?'redFont':'greenFont']">
                {{ store.chinaAdd.confirm > 0?"+":"-" }}{{ store.chinaAdd.confirm }}
              </span>
            </div>
          </section>
          <section>
            <div class='card-title'>无症状感染者</div>
            <div class="nowData">
              <span :class="[store.chinaTotal.noInfect > 0?'redFont':'greenFont']">
                {{ store.chinaTotal.noInfect }}
              </span>
            </div>
            <div class="complete">较上日
              <span :class="[store.chinaAdd.noInfect > 0?'redFont':'greenFont']">
                {{ store.chinaAdd.noInfect > 0?"+":"-" }}{{ store.chinaAdd.noInfect }}
              </span>
            </div>
          </section>
          <section>
            <div class='card-title'>境外输入</div>
            <div class="nowData">
              <span :class="[store.chinaTotal.importedCase > 0?'redFont':'greenFont']">
                {{ store.chinaTotal.importedCase }}
              </span>
            </div>
            <div class="complete">较上日
              <span :class="[store.chinaAdd.importedCase > 0?'redFont':'greenFont']">
                {{ store.chinaAdd.importedCase > 0?"+":"-" }}{{ store.chinaAdd.importedCase }}
              </span>
            </div>
          </section>
          <section>
            <div class='card-title'>累计死亡</div>
            <div class="nowData">
              <span :class="[store.chinaTotal.dead > 0?'redFont':'greenFont']">
                {{ store.chinaTotal.dead }}
              </span>
            </div>
            <div class="complete">较上日
              <span :class="[store.chinaAdd.dead > 0?'redFont':'greenFont']">
                {{ store.chinaAdd.dead > 0?"+":"-" }}{{ store.chinaAdd.dead }}
              </span>
            </div>
          </section>
        </div>
        <div class="table-card">
          <table class="table" cellspacing="0" border="1" >
            <thead>
              <tr>
                <th>地区</th>
                <th>新增确诊</th>
                <th>累计确诊</th>
                <th>治愈</th>
                <th>死亡</th>
              </tr>
            </thead>
            <transition-group enter-active-class="animate__animated animate__flipInY" tag="tbody">
              <tr :key="item.name" v-for="(item, index) in store.item">
                <td align="center">{{ item.name }}</td>
                <td align="center">{{ item.today.confirm }}</td>
                <td align="center">{{ item.total.confirm }}</td>
                <td align="center">{{ item.total.heal }}</td>
                <td align="center">{{ item.total.dead }}</td>
              </tr>
            </transition-group>
          </table>
        </div>
        
      </div>
      <div class="center" id="china">
        <!-- <div id="china" class='china'></div> -->
      </div>
      <div class="right" style="color:white">
        <div>
          <div class="charts-title">今日新增前十位城市</div>
          <div>
            <div class="echart-pie"></div>
          </div>
        </div>
        <div>
          <div class="charts-title">今日新增前十位城市</div>
          <div class="echart-line"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import {onMounted,onBeforeUnmount,ref} from 'vue'
  import {useStore} from './stores'
  import * as echarts from "echarts"
  import  "./assets/china.js"
  import  "animate.css"
  import  {geoCoordMap} from "./assets/geoMap"
  import axios from 'axios'

  // import chinaMapOptions from "./utils/chinaMapCharts"

  const store = useStore()

  // 现在 时间
  let timeFlag = null
  const time = ref(null)
  time.value = timeFormat()


  onMounted(async ()=>{
    getLocation()

    await store.getList()

    initChinaMapChart()
    initPie() 
    initLine()
    timeDeal()


  })

  function timeDeal(){
    timeFlag = setInterval(function(){
      // console.log('hi',timeFormat)
      time.value = timeFormat()
    },1000)
  }

  // 卸载 定时器
  onBeforeUnmount(()=>{
    clearInterval(timeFlag)
  })


  const initChinaMapChart = () => {
    let city = store.list.diseaseh5Shelf.areaTree[0].children
    store.item = city[1].children
    const data = city.map(v=>{
      return {
        name: v.name,
        value: geoCoordMap[v.name].concat(v.total.nowConfirm),
        children: v.children
      }
    })
    let charts = echarts.init(document.querySelector('#china') as HTMLElement)

    charts.setOption({
      geo: {
        map: "china",
        aspectScale: 0.8,
        layoutCenter: ["50%", "50%"],
        // 阴影
        layoutSize: "110%",
        itemStyle: {
          // normal: {
            areaColor: {
              type: "linear-gradient",
              x: 0,
              y: 1200,
              x2: 1000,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: "#152E6E", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#0673AD", // 50% 处的颜色
                },
              ],
              global: true, // 缺省为 false
            },
            shadowColor: "#0f5d9d",
            shadowOffsetX: 0,
            shadowOffsetY: 15,
            opacity: 0.5,
          // },
          
        },
        emphasis: {
          areaColor: "#0f5d9d",
        },

        regions: [
          {
            name: "南海诸岛",
            itemStyle: {
              areaColor: "rgba(0, 10, 52, 1)",
              borderColor: "rgba(0, 10, 52, 1)",
              // normal: {
                opacity: 0,
                label: {
                  show: false,
                  color: "#009cc9",
                },
              // },
            },
            label: {
              show: false,
              color: "#FFFFFF",
              fontSize: 12,
            },
          },
        ],
      },
      visualMap: {
        type: 'piecewise',
        pieces: [
            {min: 10000, max: 100000, label: '大于等于1000人', color: '#F44336'},
            {min: 1000, max: 10000, label: '大于等于1000人', color: '#EF5350'},
            {min: 500, max: 999, label: '确诊500-999人', color: '#E57373'},
            {min: 100, max: 499, label: '确诊100-499人', color: '#EF9A9A'},
            {min: 10, max: 99, label: '确诊10-99人', color: '#FFCDD2'},
            {min: 1, max: 9, label: '确诊1-9人', color: '#FFEBEE'},
            {min: -10000, max: 1, label: '确诊0人', color: '#4CAF50'},
        ],
        color: ['#E0022B', '#E09107', '#A3E00B']
      },
      series: [
        {
          type: "map",
          // 多选 省市
          // selectedMode: "multiple",
          map: "china",
          aspectScale: 0.8,
          layoutCenter: ["50%", "50%"], //地图位置
          // 地图大小比例
          layoutSize: "110%",
          // zoom: 1, //当前视角的缩放比例
          // // roam: true, //是否开启平游或缩放
          // scaleLimit: {
          //   //滚轮缩放的极限控制
          //   min: 1,
          //   max: 2,
          // },
          label: {
            show: true,
            color: "#FFFFFF",
            fontSize: 10,
          },
          itemStyle: {
            // normal: {
              areaColor: "#0c3653",
              borderColor: "#1cccff",
              borderWidth: 1.8,
            // },
          },
          emphasis: {
            areaColor: "#56b1da",
            label: {
              show: true,
              color: "#fff",
            },
          },
          data: data,
        },
        {
            type: 'scatter',
            coordinateSystem: 'geo',
            symbol:"pin",
            symbolSize:[40,40],
            label: {
              show: true,
              color:"#000",
              formatter(value: any) {
                return value.data?.value[2]
              }
                
            },
            itemStyle: {
              // 气泡颜色 //标志颜色
              color: '#1E90FF', 
            },
            data: data,
        },
      ],
    })

    charts.on('click', (e: any) => {
      // console.log(e)
      store.item = e.data.children
    })
  }

  const initPie = () => {
    const charts = echarts.init(document.querySelector('.echart-pie') as HTMLElement)
    charts.setOption({
      backgroundColor: "#00000080",
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: ['40%', '70%'],
          itemStyle: {
            borderRadius: 4,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '15',
              coloe:'#fff',
            }
          },
          data: store.cityDetail.map(v => {
            return {
              show:true,
              name: v.city,
              value: v.nowConfirm
            }
          })
        }
      ]
    })
  }

  const initLine = () => {
    const charts = echarts.init(document.querySelector('.echart-line') as HTMLElement)
    charts.setOption({
      backgroundColor: "#00000080",
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: store.cityDetail.map(v => v.city),
        axisLine: {
          lineStyle: {
            color: "#fff"
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: "#fff"
          }
        }
      },
      label: {
        show: true
      },
      series: [
        {
          data: store.cityDetail.map(v => v.nowConfirm),
          type: 'line',
          smooth: true
        }
      ]
    })
  }

  // 地理位置 获取
  function getLocation(){
          
          alert('获取位置信息请求');
          if (navigator.geolocation) {
              // 走到这里说明，浏览器支持geolocation，参数里有两个回调函数，一个是定位成功后的处理操作，一个是定位失败后的处理操作，另外一个参数没有研究过
              // navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
              navigator.geolocation.getCurrentPosition(showPosition);

          } else {
              // 否则浏览器不支持geolocation
              alert('您的浏览器不支持地理位置定位！');
          }
  }


  function showPosition(_position:any){
    console.log( "Latitude: " + _position.coords.latitude + "Longitude: " + _position.coords.longitude)
    // let location = _position.coords.latitude+','+_position.coords.longitude;
    let location = {
      lon:_position.coords.latitude,
      lat:_position.coords.longitude
    };

    axios({
      
      // https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1
      // http://api.tianditu.gov.cn/geocoder?postStr={'lon':116.37304,'lat':39.92594,'ver':1}&type=geocode&tk=您的密钥
      // c391a5d0a6e6fd66ae98d9f394f6d901
      
      url:`http://api.tianditu.gov.cn/geocoder?postStr={'lon':${location.lon},'lat':${location.lat},'ver':2}&type=geocode&tk=c391a5d0a6e6fd66ae98d9f394f6d901`

    }).then(res=>console.log(res.data.result.addressComponent)).catch(err=>console.log(err))
  }

  function timeFormat(dateTime = null, fmt = 'yyyy-mm-dd') {
    // 如果为null,则格式化当前时间
    if (!dateTime) dateTime = Number(new Date());
    // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
    if (dateTime.toString().length == 10) dateTime *= 1000;
    let date = new Date(dateTime);
    let ret;
    let opt = {
      "y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "h+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "s+": date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt + " " + opt["h+"] + ":" + (opt["M+"].length>1 ? opt["M+"]:("0"+opt["M+"])) + ":" + opt["s+"] ;
  }


</script>

<style scoped lang="less">
  @panelBg:rgba(0, 0 ,0 ,.5);
  @panelBgPlus:rgba(33 32 40);
  .redFont{
    color:red;
    font-weight:bold;
  }
  .greenFont{
    color:green;
    font-weight:bold;
  }

  .box{
    min-width: 1500px;
    height:100%;
    
    background:url('/img/001.jpg');
    background-size:cover;
    
    .top{
      height:8%;
      display:flex;
      justify-content:center;
      
      .infoTip{
        display:flex;
        align-items:center;
        padding:0 10px;
        border-bottom-left-radius:10px;
        border-bottom-right-radius:10px;
        color:white;
        font-weight:bold;
        background:rgba(255,255,255,0.2);

        .updateTime{}
        .other{}

        .webTitle{
          font-size:32px;
          margin:0 10px;
        }
      }
    }

    .dataBox{
      height:92%;
      display:flex;
      justify-content: space-between; 

      .left{
        flex: 1;
        max-width: 500px;
        min-width:450px;
        color:white;
        font-size:16px;
        background:@panelBg;
        display: flex;
        flex-direction: column;

        .table-card{
          height: 500px;
          overflow: auto;
          flex: 1;
        }
        .table {
          width: 100%;
          background:@panelBg;
          tr {
            th {
              font-weight:bold;
              padding: 5px;
              white-space: nowrap;
              background: @panelBgPlus;
            }
            td {
              padding: 5px 10px;
              width: 100px;
              white-space: nowrap;
            }
          }
          tr:nth-child(2n){
            background: rgba(33 32 40);
          }
        }

        .box-left-card{
          display:flex;
          justify-content:space-around;
          flex-wrap:wrap;
          background:rgba(0, 0 ,0 ,.5);


          section{
            border:1px solid black;
            border-radius:10px;
            padding:20px;
            min-width:30%;
            flex:1;
            font-size:20px;
            text-align:center;

            .complete{
              font-size:14px;
            }
            .card-title{
              font-size:16px;
            }
            .nowData{
              font-weight:bold;
              color:red;
              font-size:24px;
            }
          }
        }
      }
      .center{
        margin:10px;
        flex: 2;
        height: 100%;

        display:flex;
        justify-content: center;
        align-items: center;

      }
      .right{
        flex: 1;
        max-width: 450px;
        min-width:350px;
        

        .charts-title{
          background-color: @panelBg;
          font-weight: bold;
          text-align: center;
          font-size: 24px;
        }

        .echart-pie{
          height: 320px;
          // margin-top: 20px;
        }
        .echart-line{
          height: 320px;
          
        }
        
      }
    }
    }

    
</style>
